const BaseController = require("./base/base");
const Result = require("../utils/result");
const tools = require("../utils/tools");
const jwt = require("jsonwebtoken");
const usersModel = require("../model/users");
const logsModel = require("../model/logs");
var svgCaptcha = require('svg-captcha');
const { getTokenUser, isAdmin } = require("../middlewares/auth");
class UsersController extends BaseController {
  constructor() {
    super();
    this.key = "guoyei";
  }
  login(req, res, next) {
    setTimeout(async ()=>{
      try {
        let role = "用户"
        const { user_name, user_pwd, isadmin } = req.body;
        if (isAdmin(isadmin)) role = "管理员"
        if (!user_name || !user_pwd) return res.json(Result.fail("用户名或密码错误"));
        let userinfo = await usersModel.login({ user_name, user_pwd, role });
        if (!userinfo || userinfo.length == 0) return res.json(Result.fail("用户名或密码错误"));
        if (userinfo[0].user_state != 1) return res.json(Result.fail("用户已禁用"));
        const authorization = jwt.sign({ user_id: userinfo[0].user_id, user_name, role: userinfo[0].role }, this.key, { expiresIn: "1d" });
        //{"admin":"test","iat":1635397028,"exp":1635483428}
        let ip = tools.get_client_ip(req);
        let time = tools.getNowTime();
        let data = {
          user_last_login: time,
          user_last_ip: ip
        }
        usersModel.update(data, userinfo[0].user_id); //修改最后登录时间和IP
        logsModel.insert({user_id: userinfo[0].user_id, ip, time });// 登录记录日志
        res.json(Result.ok("success", { user_id: userinfo[0].user_id, user_name, role: userinfo[0].role, authorization }));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  verify(req, res, next) {
    setTimeout(async ()=>{
      try {
        const { user_name } = req.query;
        if (!user_name) return res.json(Result.fail("user_name错误"));
        const { authorization } = req.headers; //headers 里面的所有key都会是小写
        if (!authorization) return res.json(Result.fail("authorization错误"));
        const data = jwt.verify(authorization, this.key); //{"user_name":"admin","iat":1635349069,"exp":1635435469}
        if (user_name != data.user_name) return res.json(Result.fail("user_name不匹配"));
        res.json(Result.ok("success", data));
      } catch (err) {
        //篡改{"name":"JsonWebTokenError","message":"invalid token"}
        //过期{"name":"TokenExpiredError","message":"jwt expired","expiredAt":"2021-10-28T03:28:45.000Z"}
        res.json(Result.fail(err));
      }
    })
  }
  reg(req, res, next) {
    setTimeout(async ()=>{
      try {
        const { user_name, user_pwd } = req.body;
        if (!user_name || !user_pwd) return res.json(Result.fail("用户名或密码不能为空"));
        let ret = await usersModel.findByUsername(user_name);
        if (ret && ret.length > 0) return res.json(Result.fail("用户名已存在"));
        ret = await usersModel.reg({ ...req.body, create_by: user_name });
        !ret.insertId ?
          res.json(Result.fail("注册失败", ret)) :
          res.json(Result.ok("注册成功", ret));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  noexist(req, res, next) {
    setTimeout(async ()=>{
      try {
        const { user_name } = req.query;
        if (!user_name) return res.json(Result.fail("user_name错误"));
        let ret = await usersModel.findByUsername(user_name);
        ret && ret.length > 0 ?
          res.json(Result.fail("用户名已存在")) :
          res.json(Result.ok("success"));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  captcha(req, res, next) {
    setTimeout(async ()=>{
      const { width = "120", height = "40" } = req.query;
      var codeConfig = { size: 4, ignoreChars: 'abh0QOoqg9l1iv', noise: 2, color: true, };
      if (width) codeConfig["width"] = width;
      if (height) codeConfig["height"] = height;
      var captcha = svgCaptcha.create(codeConfig);
      req.session.captcha = captcha.text.toLowerCase();
      res.set('Content-Type', 'image/svg+xml');
      res.send(captcha.data);
    })
  }
  vcaptcha(req, res, next) {
    setTimeout(async ()=>{
      try {
        let { vcode } = req.params;
        let { captcha } = req.session;
        console.log(vcode, captcha);
        if (!vcode || !captcha) return res.json(Result.fail("没有验证码"));
        captcha = captcha.toLowerCase();
        vcode = vcode.toLowerCase();
        if (vcode != captcha) return res.json(Result.fail("验证码错误"));
        res.json(Result.ok());
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  myinfo(req, res, next) {
    setTimeout(async ()=>{
      const { username } = req.params;
      let { user_name = "" } = getTokenUser(req);
      if (!user_name || !username) return res.json(Result.fail("请传递用户名参数"));
      if (user_name != username) return res.json(Result.fail("用户名有误"));
      let ret = await usersModel.findByUsername(user_name);
      delete ret.user_pwd;
      delete ret.user_pay_pwd;
      if (!ret || ret.length == 0) {
        return res.json(Result.fail("信息不存在"));
      }
      //删除数据中的密码字段
      delete ret[0].user_pwd;
      delete ret[0].user_pay_pwd;
      res.json(Result.ok("success", ret[0]))
    })
  }
  findUsersList(req, res, next) {
    setTimeout(async ()=>{
      try {
        let { role: isadmin = "" } = getTokenUser(req);
        if (!isAdmin(isadmin)) return res.json(Result.fail("你没有管理员权限", []));
        let { pagesize = 10, page = 1, user_name = '', role = '' } = req.query;
        if (!pagesize) pagesize = 10;
        if (!page) page = 1;
        let count = await usersModel.getCount({ pagesize, page, user_name, role });
        let ret = await usersModel.findUsersList({ pagesize, page, user_name, role });
        res.json(Result.ok("success", { total: count[0].count, list: ret }));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  findById(req, res, next) {
    setTimeout(async ()=>{
      try {
        let { id } = req.params;
        let { role = '', user_id = 0 } = getTokenUser(req);
        if (!isAdmin(role)) id = user_id; //不是管理员只能查自己的
        let ret = await usersModel.findById(id);
        res.json(Result.ok("success", ret));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  insert(req, res, next) {
    setTimeout(async ()=>{
      try {
        let { role: isadmin = "" } = getTokenUser(req);
        if (!isAdmin(isadmin)) return res.json(Result.fail("你没有管理员权限", []));
        const { user_name, user_pwd, role } = req.body;
        if (!user_name || !user_pwd) return res.json(Result.fail("用户名或密码不能为空"));
        if (role != "用户" && role != "管理员") { req.body.role = "用户" } //处理角色字段
        let ret = await usersModel.findByUsername(user_name);
        if (ret && ret.length > 0) return res.json(Result.fail("用户名已存在"));
        ret = await usersModel.reg({...req.body, create_by: user_name });
        !ret.insertId ?
          res.json(Result.fail("添加失败", ret)) :
          res.json(Result.ok("添加成功", ret));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  update(req, res, next){
    setTimeout(async ()=>{
      try {
        let { role: isadmin = "" } = getTokenUser(req);
        if (!isAdmin(isadmin)) return res.json(Result.fail("你没有管理员权限", []));
        const { id } = req.params;
        delete req.body.user_name; //用户名不能修改,干掉这个字段
        // delete req.body.role; //角色不能修改,干掉这个字段
        let ret = await usersModel.update({...req.body}, id);
        !ret.affectedRows ?
          res.json(Result.fail("修改失败", ret)) :
          res.json(Result.ok("修改成功", ret));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  delById(req, res, next){
    setTimeout(async ()=>{
      try {
        let { role: isadmin = "" } = getTokenUser(req);
        if (!isAdmin(isadmin)) return res.json(Result.fail("你没有管理员权限", []));
        const { id } = req.params;
        let ret = await usersModel.delById(id);
        !ret.affectedRows ?
          res.json(Result.fail("删除失败", ret)) :
          res.json(Result.ok("删除成功", ret));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  editpwd(req, res, next){
    setTimeout(async ()=>{
      try {
        let { user_id, role: isadmin = "" } = getTokenUser(req);
        // if (!isAdmin(isadmin)) return res.json(Result.fail("你没有管理员权限", []));
        const { id } = req.params;  //用户ID
        if (user_id != id) return res.json(Result.fail("用户ID有误,数据篡改"));

        const { user_pwd, new_pwd } = req.body;
        if (!user_pwd) return res.json(Result.fail("原密码不能为空"));
        if (!new_pwd) return res.json(Result.fail("新密码不能为空"));

        let ret = await usersModel.findById(id);
        if(!ret || ret.length == 0) return res.json(Result.fail("用户不存在"));

        if (user_pwd != ret[0].user_pwd) return res.json(Result.fail("原密码错误"));

        ret = await usersModel.update({user_pwd: new_pwd}, id);
        !ret.affectedRows ?
          res.json(Result.fail("修改失败", ret)) :
          res.json(Result.ok("修改成功", ret));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
}
module.exports = new UsersController().resolve();